package com.jds.test.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;

import java.util.List;

/**
 * Created by sunyuming on 18/9/13.
 */
public class WebSocketFrameDecoder extends MessageToMessageDecoder<WebSocketFrame> {

    @Override
    protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception {
        if(frame instanceof TextWebSocketFrame) {
            TextWebSocketFrame tframe = (TextWebSocketFrame)frame;
            // 内存泄漏
        //    out.add(tframe.retain().text());    // 虽然 frame 会自动释放，且往下传递的是String对象，所以让MessgeToMessageDecoder自动释放掉fram
            out.add(tframe.text());
        } else {
            // 不必要，但这种情况下release无害
        //    frame.release();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }
}